import { ref, reactive, onMounted } from 'vue'
import type { UserProfile, UserProfileResponse, UpdateProfileParams } from '@/types/profile'
import { profileApi } from '@/api/user/profile'
import { useUserStore } from '@/stores/user'
import router from '@/router'
import { ElMessage } from 'element-plus'
import dayjs from 'dayjs'

export const useProfile = () => {
  const userStore = useUserStore()
  const profileInfo = ref<UserProfile>({} as UserProfile)
  const loading = ref(false)
  const submitting = ref(false)
  
  const profileForm = reactive<UpdateProfileParams>({
    nickname: '',
    phone: '',
    email: '',
    avatar: ''
  })

  const fetchProfile = async () => {
    loading.value = true
    try {
      console.log('开始获取个人资料')
      const response = await profileApi.getInfo()
      console.log('获取个人资料响应:', response)

      if (response.status === 200) {
        const { password, ...rest } = response.data as UserProfileResponse
        console.log('处理后的个人资料:', rest)
        
        profileInfo.value = rest
        // 初始化表单数据
        Object.assign(profileForm, {
          nickname: rest.nickname,
          phone: rest.phone,
          email: rest.email,
          avatar: rest.avatar
        })
        console.log('表单数据已更新:', profileForm)
      } else {
        console.error('获取个人资料失败: HTTP状态码', response.status)
        ElMessage.error('获取个人资料失败')
      }
    } catch (error: any) {
      console.error('获取个人资料错误:', error)
      if (error.response) {
        console.error('错误响应:', error.response.data)
        ElMessage.error(error.response.data.message || '获取个人资料失败')
      } else {
        console.error('网络错误:', error.message)
        ElMessage.error('网络错误，请稍后重试')
      }
    } finally {
      loading.value = false
    }
  }

  const handleUpdateProfile = async () => {
    if (submitting.value) return
    
    // 添加简单的表单验证
    if (!profileForm.nickname?.trim()) {
      ElMessage.warning('昵称不能为空')
      return
    }
    
    if (profileForm.phone && !/^1[3-9]\d{9}$/.test(profileForm.phone)) {
      ElMessage.warning('请输入正确的手机号')
      return
    }
    
    if (profileForm.email && !/^[\w-]+(\.[\w-]+)*@[\w-]+(\.[\w-]+)+$/.test(profileForm.email)) {
      ElMessage.warning('请输入正确的邮箱')
      return
    }

    submitting.value = true
    try {
      const response = await profileApi.updateInfo(profileForm)
      if (response.data.code === 200) {
        ElMessage.success('更新成功')
        await fetchProfile()
      } else {
        ElMessage.error(response.data.message || '更新失败')
      }
    } catch (error) {
      console.error('更新个人资料失败:', error)
      ElMessage.error('更新个人资料失败')
    } finally {
      submitting.value = false
    }
  }

  const formatDate = (date: string) => {
    return dayjs(date).format('YYYY-MM-DD HH:mm:ss')
  }

  onMounted(() => {
    if (!userStore.isLoggedIn) {
      router.push('/login')
      return
    }
    fetchProfile()
  })

  return {
    profileInfo,
    profileForm,
    loading,
    submitting,
    handleUpdateProfile,
    formatDate
  }
} 